package com.java.redis;

import org.junit.Test;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.net.URL;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class MainApplication {
    Jedis client = new Jedis("localhost");
    @Test
    public void connectTest(){
        Jedis client = new Jedis("localhost");
        System.out.println(client.ping());
    }

    @Test
    public void operate() throws InterruptedException {
        Long lock = client.setnx("lock", "1");
        System.out.println(lock);
        Long lock1 = client.setnx("lock", "1");
        System.out.println(lock1);
        Long lock2 = client.del("lock");
        System.out.println(lock2);
        Long lock3 = client.setnx("lock", "1");
        System.out.println(lock3);
        System.out.println("===================");
        System.out.println(client.expire("lock", 10));
        System.out.println(client.get("lock"));
        TimeUnit.SECONDS.sleep(11);
        System.out.println(client.get("lock"));
    }

    public void jedisPollTest(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        new JedisPool("localhost",6379);
    }

    @Test
    public void redisson(){
        // 构造redisson实现分布式锁必要的Config
        Config config = new Config();
        config.useMasterSlaveServers()
                .setMasterAddress("127.0.0.1:6379")
                .addSlaveAddress("127.0.0.1:6377", "127.0.0.1:6378");
        // 构造RedissonClient
        RedissonClient client = Redisson.create(config);
        // 设置锁定资源名称
        RLock disLock = client.getLock("DISLOCK");
        boolean isLock;
        try{
            isLock = disLock.tryLock(500, 15000, TimeUnit.MILLISECONDS);
            if (isLock){
                //TODO if get lock success, do something;
                Thread.sleep(15000);
            }
        }catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 无论如何, 最后都要解锁
            disLock.unlock();
        }
    }
}
